package com.adream.scalpel.security.server.system;

import org.springframework.security.AuthenticationException;
import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

public class ScalpelAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        HTTPResponseWrapper redirectResponseWrapper = new HTTPResponseWrapper(response);

        filterChain.doFilter(request, redirectResponseWrapper);

        if (redirectResponseWrapper.getRedirect() != null) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain;charset=utf-8");

            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Pragma", "no-cache");

            String redirectURL = redirectResponseWrapper.getRedirect();
            String content;
            if (redirectURL.indexOf("login_error=1") > -1) {
                // Could not log in;
                content = "error:"
                        + ((AuthenticationException) request.getSession().getAttribute(
                                AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY)).getMessage();
                // TODO
                // We need to log this failure for security audits.
                // That needs to happen here.
            } else {
                // Login successful.
                content = "url:" + redirectURL;
            }
            response.getOutputStream().write(content.getBytes("UTF-8"));
        }
    }
}
